import OSS from "ali-oss";
import "multer";

interface HeadError extends Error {
    code: string;
    name: string;
}

export const uploadFile = (file: Express.Multer.File, name?: string): Promise<{ name: string; url: string }> => {
    // 初始化OSS客户端。请将以下参数替换为您自己的配置信息。
    const client = new OSS({
        region: "oss-cn-hangzhou", // 示例：'oss-cn-hangzhou'，填写Bucket所在地域。
        accessKeyId: process.env.OSS_ACCESS_KEY_ID!, // 确保已设置环境变量OSS_ACCESS_KEY_ID。
        accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET!, // 确保已设置环境变量OSS_ACCESS_KEY_SECRET。
        bucket: "n-fs", // 示例：'my-bucket-name'，填写存储空间名称。
    });
    // 检查文件是否存在
    const checkFileExists = async (objectName: string) => {
        try {
            await client.head(objectName);
            return true;
        } catch (err) {
            const error = err as HeadError;
            if (["NoSuchKey", "AccessDenied", "NoSuchBucket"].includes(error.code)) {
                return false;
            }
            throw err;
        }
    };
    return new Promise(async (resolve, reject) => {
        const { originalname: oName } = file;
        const originalname = Buffer.from(oName, "latin1")
            .toString("utf-8")
            .split(".")
            .filter((_, index, arr) => index !== arr.length - 1)
            .join();
        let fileName = name || originalname || Date.now().toString();
        try {
            const checkRes = await checkFileExists(fileName);
            if (checkRes) fileName = `${Date.now()}_${fileName}`;
            const uploadResult = await client.put(`/van-fullstack-admin/${fileName}`, file.buffer, {
                headers: {
                    "Content-Type": file.mimetype, // 根据实际文件类型设置
                    "Content-Disposition": `inline`, // 阿里云OSS已禁止预览图片https://help.aliyun.com/noticelist/articleid/1060057906.html
                },
            });
            const { name, url, res: ossRes } = uploadResult;
            if (ossRes.status !== 200) return reject(Error("上传失败"));
            resolve({ name, url });
        } catch (error) {
            // 在此处添加错误处理逻辑。
            reject(Error("上传失败"));
        }
    });
};
